/**
 * Copyright 2019 吉鼎科技.

 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cn.easyplatform.dos;

import cn.easyplatform.messages.vos.RoleVo;
import cn.easyplatform.type.DeviceType;

import java.io.Serializable;
import java.util.*;


/**
 * @author <a href="mailto:davidchen@epclouds.com">littleDog</a> <br/>
 * @since 2.0.0 <br/>
 */
public class UserDo implements Serializable, Cloneable {

    /**
     * 默认的最大登陆密码错误次数，可以由easyplatform.conf或project配置
     */
    public static final int DEFAULT_MAX_LOGIN_FAILED_TIMES = 0x06;

    /**
     * 默认的用户超时时间，可以由easyplatform.conf或project配置
     */
    public static final int DEFAULT_TIMEOUT = 0x05;

    /**
     * 用户状态：未激活
     */
    public final static int STATE_NOT_ACTIVATED = 0x00;

    /**
     * 用户状态：已激活
     */
    public final static int STATE_ACTIVATED = 0x01;

    /**
     * 用户状态：被锁定
     */
    public final static int STATE_LOCK = 0x02;

    /**
     * 用户在线状态：不在线
     */
    public final static int ONLINE_NONE = 0x00;

    /**
     * 用户在线状态：本身在线
     */
    public final static int ONLINE_SELF = 0x01;

    /**
     * 用户在线状态：用户在其它设备上
     */
    public final static int ONLINE_OTHER = 0x02;

    /**
     *
     */
    private static final long serialVersionUID = 9076657626845688263L;

    /**
     * 用户id
     */
    private String id;

    /**
     * 名称
     */
    private String name;

    /**
     * 密码
     */
    private String password;

    //原始密码
    private String originalPassword;

    /**
     * 类型
     */
    private int type;

    /**
     * 客户端ip
     */
    private String ip;

    /**
     * 所在地区
     */
    private String locale;

    /**
     * 登陆时间
     */
    private Date loginDate;

    /**
     * 机构id
     */
    private OrgDo org;

    /**
     * 用户自身的工作空间，由已用户可能会跨项目，所以根据所在的db生成工作空间
     */
    private String workspace;

    /**
     * 具体工作路径
     */
    private String workPath;

    /**
     * 用户所属的角色列表
     */
    private String[] roles;

    /**
     * 附加信息，由用户自定义
     */
    private Map<String, Object> extraInfo;

    /**
     *
     */
    private boolean debugEnabled = false;

    /**
     * 有效开始日期
     */
    private Date validDate;

    /**
     * 有效天数
     */
    private int validDays;

    /**
     * 最后操作时间
     */
    private Date lastAccessTime;

    /**
     * 超时时间，单位分
     */
    private int timeout;

    /**
     * 设备类型
     */
    private DeviceType deviceType;

    /**
     * 用户状态
     */
    private int state;

    /**
     * 开始有效日期
     */
    private Date validStartDate;

    /**
     * 失效日
     */
    private Date validEndDate;

    /**
     * 是否有打开Msn
     */
    private boolean openMsn;

    /**
     * 生成sys_event_info等表的主键回调接口
     */
    private IdCallback cb;
    /**
     * 会话id
     */
    private Serializable sessionId;

    /**
     * Event级别
     */
    private int logLevel;

    /**
     * 用户页面订清单
     */
    private Set<String> subscribes;

    /**
     * @return the id
     */
    public String getId() {
        return id;
    }

    /**
     * @param id the id to set
     */
    public void setId(String id) {
        this.id = id;
    }

    /**
     * @return the name
     */
    public String getName() {
        return name;
    }

    /**
     * @param name the name to set
     */
    public void setName(String name) {
        this.name = name;
    }

    /**
     * @return the password
     */
    public String getPassword() {
        return password;
    }

    /**
     * @param password the password to set
     */
    public void setPassword(String password) {
        this.password = password;
    }

    public String getOriginalPassword() {
        return originalPassword;
    }

    public void setOriginalPassword(String originalPassword) {
        this.originalPassword = originalPassword;
    }

    /**
     * @return the ip
     */
    public String getIp() {
        return ip;
    }

    /**
     * @param ip the ip to set
     */
    public void setIp(String ip) {
        this.ip = ip;
    }

    /**
     * @return the locale
     */
    public String getLocale() {
        return locale;
    }

    /**
     * @param locale the locale to set
     */
    public void setLocale(String locale) {
        this.locale = locale.toLowerCase();
    }

    /**
     * @return the loginDate
     */
    public Date getLoginDate() {
        return loginDate;
    }

    /**
     * @param loginDate the loginDate to set
     */
    public void setLoginDate(Date loginDate) {
        this.loginDate = loginDate;
        this.lastAccessTime = loginDate;
    }

    /**
     * @return
     */
    public String getWorkspace() {
        return workspace;
    }

    /**
     * @param workspace
     */
    public void setWorkspace(String workspace) {
        this.workspace = workspace;
    }

    /**
     * @return
     */
    public Map<String, Object> getExtraInfo() {
        return extraInfo;
    }

    /**
     * @param extraInfo
     */
    public void setExtraInfo(Map<String, Object> extraInfo) {
        this.extraInfo = extraInfo;
    }

    /**
     * @return
     */
    public String[] getRoles() {
        return roles;
    }

    /**
     * @param roles
     */
    public void setRoles(List<RoleVo> roles) {
        this.roles = new String[roles.size()];
        for (int i = 0; i < roles.size(); i++)
            this.roles[i] = roles.get(i).getId();
    }

    public void setRoles(String[] roles) {
        this.roles = roles;
    }

    public OrgDo getOrg() {
        return org;
    }

    public void setOrg(OrgDo org) {
        this.org = org;
    }

    public boolean isDebugEnabled() {
        return debugEnabled;
    }

    public void setDebugEnabled(boolean debugEnabled) {
        this.debugEnabled = debugEnabled;
    }

    /**
     * @return the workPath
     */
    public String getWorkPath() {
        return workPath;
    }

    /**
     * @param workPath the workPath to set
     */
    public void setWorkPath(String workPath) {
        this.workPath = workPath;
    }

    /**
     * @return the type
     */
    public int getType() {
        return type;
    }

    /**
     * @param type the type to set
     */
    public void setType(int type) {
        this.type = type;
    }

    /**
     * @return the validDate
     */
    public Date getValidDate() {
        return validDate;
    }

    /**
     * @param validDate the validDate to set
     */
    public void setValidDate(Date validDate) {
        this.validDate = validDate;
    }

    /**
     * @return the validDays
     */
    public int getValidDays() {
        return validDays;
    }

    /**
     * @param validDays the validDays to set
     */
    public void setValidDays(int validDays) {
        this.validDays = validDays;
    }

    /**
     * @param lastAccessTime the lastAccessTime to set
     */
    public void setLastAccessTime(Date lastAccessTime) {
        this.lastAccessTime = lastAccessTime;
    }

    /**
     * @param timeout the timeout to set
     */
    public void setTimeout(int timeout) {
        this.timeout = timeout;
    }

    public int getTimeout() {
        return timeout;
    }

    /**
     * 获取当前用户所属的机构或角色
     *
     * @return
     */
    public String[] getGroups() {
        String[] groups = new String[roles.length + 1];
        System.arraycopy(roles, 0, groups, 0, roles.length);
        groups[roles.length] = org.getId();
        return groups;
    }

    /**
     * @return the deviceType
     */
    public DeviceType getDeviceType() {
        return deviceType;
    }

    /**
     * @param deviceType the deviceType to set
     */
    public void setDeviceType(DeviceType deviceType) {
        this.deviceType = deviceType;
    }

    /**
     * @return the state
     */
    public int getState() {
        return state;
    }

    /**
     * @param state the state to set
     */
    public void setState(int state) {
        this.state = state;
    }

    /**
     * 检查用户是否超时
     *
     * @return
     */
    public boolean checkValid() {
        if (lastAccessTime == null || (deviceType != DeviceType.AJAX && deviceType != DeviceType.MOBILE))
            return true;
        //只有客户端是浏览器的才检查
        if (timeout > 0) {
            long expireTimeMillis = System.currentTimeMillis() - timeout * 1000
                    * 60;
            Date expireTime = new Date(expireTimeMillis);
            return lastAccessTime.after(expireTime);
        } else
            return true;
    }

    /**
     * @param cb
     */
    public void setIdCallback(IdCallback cb) {
        this.cb = cb;
    }

    /**
     * @return
     */
    public long getEventId() {
        return cb.getId("sys_event_info");
    }

    /**
     * @return
     */
    public boolean isOpenMsn() {
        return openMsn;
    }

    /**
     * @param openMsn
     */
    public void setOpenMsn(boolean openMsn) {
        this.openMsn = openMsn;
    }

    /**
     * @return the validStartDate
     */
    public Date getValidStartDate() {
        return validStartDate;
    }

    /**
     * @param validStartDate the validStartDate to set
     */
    public void setValidStartDate(Date validStartDate) {
        this.validStartDate = validStartDate;
    }

    /**
     * @return the validEndDate
     */
    public Date getValidEndDate() {
        return validEndDate;
    }

    /**
     * @param validEndDate the validEndDate to set
     */
    public void setValidEndDate(Date validEndDate) {
        this.validEndDate = validEndDate;
    }

    public Serializable getSessionId() {
        return sessionId;
    }

    public void setSessionId(Serializable sessionId) {
        this.sessionId = sessionId;
    }

    public int getLogLevel() {
        return logLevel;
    }

    public void setLogLevel(int logLevel) {
        this.logLevel = logLevel;
    }

    public void subscribe(String name) {
        if (subscribes == null)
            subscribes = new HashSet<>();
        subscribes.add(name);
    }

    public void unsubscribe(String name) {
        if (subscribes != null)
            subscribes.remove(name);
    }

    public void reset() {
        if (subscribes != null)
            subscribes.clear();
        this.debugEnabled = false;
    }

    public boolean isSubscribed(String name) {
        return subscribes != null && subscribes.contains(name);
    }

    public UserDo clone() {
        try {
            return (UserDo) super.clone();
        } catch (Exception e) {
        }
        return null;
    }
}
